package com.yuyang.gulimall.seckill.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author yu yang
 * @date 2023/2/4 -17:03
 */
@Configuration
public class FeignConfig {

    //解决feign远程调用丢失请求头
    // feign远程调用创建RequestTemplate发送请求，发送请求前执行RequestInterceptor的apply方法进行增强
    @Bean("requestInterceptor")
    RequestInterceptor requestInterceptor(){
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                //spring提供的RequestContextHolder获取当前请求
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if (requestAttributes != null) {
                   HttpServletRequest request = requestAttributes.getRequest();
                    //同步请求头 将旧的请求携带的header添加到feign创建的新请求
                    String cookies = request.getHeader("Cookie");
                    requestTemplate.header("Cookie",cookies);
                }

            }
        };
    }

}
